﻿using System;
using System.Collections.Generic;
using csvm.datamodel.contract;
using csvm.pagebuilder.contract;

namespace csvm.pagebuilder
{
    public class PageBuilder : IPageBuilder
    {
        private readonly int pageSize;

        internal PageBuilder(int pageSize)
        {
            this.pageSize = pageSize;
        }

        public PageBuilder(): this(20)
        {
        }


        public void ProcessBuildPages(IEnumerable<Record> records) {
            OnLoadPages(BuildPages(records));
        }

        public IEnumerable<Page> BuildPages(IEnumerable<Record> records) {

            var recordListe = new List<Record>();
            var i = 0;
            foreach (var record in records) {

                recordListe.Add(record);
                if (i++ == pageSize - 1) {
                    i = 0;
                    yield return new Page(recordListe);
                    recordListe.Clear();

                }
            }

            yield return new Page(recordListe);
        }

        public event Action<IEnumerable<Page>> OnLoadPages;
    }
}
